from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render

from .models import Opera
from .forms import NameForm


# Create your views here.
def index(request):
    opera_list = Opera.objects.order_by('-operaId')
    context = {'opera_list':opera_list}
    return render(request,"artworks/index.html",context)

def detail(request, artwork_pk):
    opera = get_object_or_404(Opera,pk=artwork_pk)
    context = {'opera': opera}
    return render(request, "artworks/detail.html",context)

def add(request):
    return HttpResponse("Add Page")

def edit(request, artwork_id):
    return HttpResponse("Edit Page %s" % artwork_id)

def delete(request, artwork_pk):
    opera = Opera.objects.get(pk=artwork_pk).delete()
    return HttpResponseRedirect("/artworks")


def demo(request):
    template = 'artworks/demo.html'
    return render(request,template)

def demo_bootstrap(request):
    template = 'artworks/demo_bootstrap.html'
    opera_list = Opera.objects.all().order_by('-operaId')
    context = {'opera_list':opera_list}
    return render(request,template,context)

def demo_pico(request):
    template = 'artworks/demo_pico.html'
    return render(request,template)

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponse('<html><head><meta charset="UTF-8"></head> <body>表单提交成功, Get form data : %s</body></html>' % form.cleaned_data['your_name'])

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'artworks/get_name.html', {'form': form})